<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>商品详情 - 助农购物网站</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .review-card {
            margin-bottom: 20px;
            border: 1px solid #dee2e6;
            border-radius: 5px;
        }
        .rating {
            color: #ffc107;
            font-size: 20px;
        }
        .review-images {
            margin-top: 10px;
        }
        .review-images img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            margin-right: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container mt-4">
        <c:if test="${product != null}">
            <div class="row">
                <div class="col-md-6">
                    <c:if test="${product.imageUrl != null && !empty product.imageUrl}">
                        <img src="${product.imageUrl}" class="img-fluid" alt="${product.productName}">
                    </c:if>
                </div>
                <div class="col-md-6">
                    <h2>${product.productName}</h2>
                    <p class="text-muted">分类：${product.category}</p>
                    <h3 class="text-danger">¥${product.price}</h3>
                    <p>库存：${product.stock}</p>
                    <p>${product.description}</p>
                    <div class="mt-4">
                        <c:if test="${sessionScope.user != null}">
                            <div class="mb-3">
                                <label for="quantity" class="form-label">购买数量：</label>
                                <input type="number" class="form-control" id="quantity" value="1" min="1" max="${product.stock}" style="width: 150px; display: inline-block;">
                            </div>
                            <button type="button" class="btn btn-primary btn-lg" onclick="openPurchaseModal()">立即购买</button>
                            <button type="button" class="btn btn-success btn-lg ms-2" onclick="addToCart()">加入购物车</button>
                        </c:if>
                        <a href="${pageContext.request.contextPath}/client/index" class="btn btn-secondary">返回商品列表</a>
                    </div>
                </div>
            </div>
            
            <!-- 商品评价区域 -->
            <div class="row mt-5">
                <div class="col-md-12">
                    <h4>商品评价</h4>
                    
                    <c:if test="${reviews != null && !empty reviews}">
                        <c:forEach var="review" items="${reviews}">
                            <div class="card review-card">
                                <div class="card-body">
                                    <div class="mb-2">
                                        <c:if test="${review.user != null}">
                                            <strong>${review.user.username}</strong>
                                            <c:choose>
                                                <c:when test="${review.user.userType == 0}">
                                                    <span class="badge bg-secondary ms-2">普通用户</span>
                                                </c:when>
                                                <c:when test="${review.user.userType == 1}">
                                                    <span class="badge bg-primary ms-2">商户</span>
                                                </c:when>
                                                <c:when test="${review.user.userType == 2}">
                                                    <span class="badge bg-danger ms-2">管理员</span>
                                                </c:when>
                                            </c:choose>
                                        </c:if>
                                        <c:if test="${review.user == null}">
                                            <strong>匿名用户</strong>
                                        </c:if>
                                        <span class="rating ms-2">
                                            <c:forEach begin="1" end="${review.rating}">★</c:forEach>
                                            <c:forEach begin="${review.rating+1}" end="5">☆</c:forEach>
                                        </span>
                                        <span class="text-muted ms-2">
                                            <fmt:formatDate value="${review.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/>
                                        </span>
                                    </div>
                                    <p class="card-text">${review.content}</p>
                                    
                                    <c:if test="${review.images != null && !empty review.images}">
                                        <div class="review-images">
                                            <c:forTokens items="${review.images}" delims="," var="image">
                                                <img src="${image}" alt="评价图片" onclick="window.open('${image}', '_blank')">
                                            </c:forTokens>
                                        </div>
                                    </c:if>
                                </div>
                            </div>
                        </c:forEach>
                    </c:if>
                    
                    <c:if test="${reviews == null || empty reviews}">
                        <div class="alert alert-info">
                            <p>暂无评价</p>
                        </div>
                    </c:if>
                </div>
            </div>
        </c:if>
        
        <c:if test="${product == null}">
            <div class="alert alert-warning">
                <p>商品不存在或已下架</p>
                <a href="${pageContext.request.contextPath}/client/index" class="btn btn-secondary">返回商品列表</a>
            </div>
        </c:if>
    </div>
    
    <!-- 支付模态框 -->
    <div class="modal fade" id="purchaseModal" tabindex="-1" aria-labelledby="purchaseModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="purchaseModalLabel">选择支付方式</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="balanceCheckResult" class="alert" style="display: none;"></div>
                    <div class="mb-3">
                        <label class="form-label">商品信息：</label>
                        <p class="mb-1">${product.productName}</p>
                        <p class="mb-1">单价：¥<span id="modalPrice">${product.price}</span></p>
                        <p class="mb-1">数量：<span id="modalQuantity">1</span></p>
                        <p class="mb-1"><strong>总价：¥<span id="modalTotal">${product.price}</span></strong></p>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">支付方式：</label>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="paymentMethod" id="paymentAlipay" value="支付宝" checked>
                            <label class="form-check-label" for="paymentAlipay">
                                <i class="bi bi-wallet2"></i> 支付宝
                            </label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="paymentMethod" id="paymentWechat" value="微信支付">
                            <label class="form-check-label" for="paymentWechat">
                                <i class="bi bi-wechat"></i> 微信支付
                            </label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmPurchaseBtn" onclick="confirmPurchase()">确认支付</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        let purchaseModal;
        
        // 页面加载完成后初始化模态框
        document.addEventListener('DOMContentLoaded', function() {
            purchaseModal = new bootstrap.Modal(document.getElementById('purchaseModal'));
        });
        
        // 打开购买模态框
        function openPurchaseModal() {
            const quantity = parseInt(document.getElementById('quantity').value) || 1;
            const price = parseFloat('${product.price}');
            const total = price * quantity;
            
            // 更新模态框中的信息
            document.getElementById('modalQuantity').textContent = quantity;
            document.getElementById('modalTotal').textContent = total.toFixed(2);
            
            // 显示模态框
            purchaseModal.show();
            
            // 校验余额
            checkBalance(quantity);
        }
        
        // 校验余额
        function checkBalance(quantity) {
            const productId = ${product.productId};
            const balanceResultDiv = document.getElementById('balanceCheckResult');
            
            fetch('${pageContext.request.contextPath}/client/product?action=checkBalance&productId=' + productId + '&quantity=' + quantity)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const sufficient = data.sufficient;
                        const balance = parseFloat(data.balance || 0);
                        const totalAmount = parseFloat(data.totalAmount || 0);
                        
                        if (sufficient) {
                            balanceResultDiv.className = 'alert alert-success';
                            balanceResultDiv.innerHTML = '余额充足，当前余额：¥' + balance.toFixed(2);
                            balanceResultDiv.style.display = 'block';
                            document.getElementById('confirmPurchaseBtn').disabled = false;
                        } else {
                            balanceResultDiv.className = 'alert alert-danger';
                            balanceResultDiv.innerHTML = '余额不足！当前余额：¥' + balance.toFixed(2) + '，需要支付：¥' + totalAmount.toFixed(2);
                            balanceResultDiv.style.display = 'block';
                            document.getElementById('confirmPurchaseBtn').disabled = true;
                        }
                    } else {
                        balanceResultDiv.className = 'alert alert-warning';
                        balanceResultDiv.innerHTML = data.message || '校验失败';
                        balanceResultDiv.style.display = 'block';
                        document.getElementById('confirmPurchaseBtn').disabled = true;
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    balanceResultDiv.className = 'alert alert-danger';
                    balanceResultDiv.innerHTML = '校验余额时发生错误';
                    balanceResultDiv.style.display = 'block';
                    document.getElementById('confirmPurchaseBtn').disabled = true;
                });
        }
        
        // 确认购买
        function confirmPurchase() {
            const productId = '${product.productId}';
            const quantityInput = document.getElementById('quantity');
            const quantity = parseInt(quantityInput.value) || 1;
            const paymentMethodInput = document.querySelector('input[name="paymentMethod"]:checked');
            
            if (!paymentMethodInput) {
                alert('请选择支付方式');
                return;
            }
            
            const paymentMethod = paymentMethodInput.value;
            
            // 验证参数
            if (!productId || productId === '' || isNaN(parseInt(productId))) {
                alert('商品ID错误：' + productId);
                console.error('Invalid productId:', productId);
                return;
            }
            
            if (isNaN(quantity) || quantity < 1) {
                alert('购买数量错误');
                return;
            }
            
            // 使用URLSearchParams构建application/x-www-form-urlencoded格式的数据
            const params = new URLSearchParams();
            params.append('productId', productId.toString());
            params.append('quantity', quantity.toString());
            params.append('paymentMethod', paymentMethod);
            
            // 禁用按钮防止重复提交
            const confirmBtn = document.getElementById('confirmPurchaseBtn');
            confirmBtn.disabled = true;
            confirmBtn.textContent = '处理中...';
            
            fetch('${pageContext.request.contextPath}/client/product?action=purchase', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('HTTP error! status: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                // 恢复按钮
                confirmBtn.disabled = false;
                confirmBtn.textContent = '确认支付';
                
                if (data.success) {
                    alert('购买成功！订单号：' + data.orderNo);
                    purchaseModal.hide();
                    // 可以选择跳转到订单页面
                    window.location.href = '${pageContext.request.contextPath}/client/order?action=list';
                } else {
                    alert(data.message || '购买失败');
                    if (data.message && data.message.includes('余额不足')) {
                        // 重新校验余额
                        checkBalance(quantity);
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                // 恢复按钮
                confirmBtn.disabled = false;
                confirmBtn.textContent = '确认支付';
                alert('购买时发生错误，请稍后重试：' + error.message);
            });
        }
        
        // 监听数量变化，重新校验余额
        document.getElementById('quantity').addEventListener('change', function() {
            if (purchaseModal && purchaseModal._isShown) {
                const quantity = parseInt(this.value) || 1;
                const price = parseFloat('${product.price}');
                const total = price * quantity;
                document.getElementById('modalQuantity').textContent = quantity;
                document.getElementById('modalTotal').textContent = total.toFixed(2);
                checkBalance(quantity);
            }
        });
        
        // 加入购物车
        function addToCart() {
            const productId = '${product.productId}';
            const quantityInput = document.getElementById('quantity');
            const quantity = parseInt(quantityInput.value) || 1;
            
            if (quantity <= 0) {
                alert('数量必须大于0');
                return;
            }
            
            if (quantity > ${product.stock}) {
                alert('库存不足');
                return;
            }
            
            const params = new URLSearchParams();
            params.append('productId', productId);
            params.append('quantity', quantity);
            
            fetch('${pageContext.request.contextPath}/client/cart?action=add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('已添加到购物车');
                    // 更新购物车数量
                    updateCartCount();
                } else {
                    alert(data.message || '添加失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加失败，请重试');
            });
        }
        
        // 更新购物车数量
        function updateCartCount() {
            fetch('${pageContext.request.contextPath}/client/cart?action=count')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const cartCountEl = document.getElementById('cartCount');
                        if (cartCountEl) {
                            cartCountEl.textContent = data.count;
                            if (data.count > 0) {
                                cartCountEl.style.display = 'inline';
                            } else {
                                cartCountEl.style.display = 'none';
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
    </script>
</body>
</html>



